package com.questionnaire.service.impl;


import com.questionnaire.dao.AnswerRepository;
import com.questionnaire.dao.UserRepository;
import com.questionnaire.model.Answer;
import com.questionnaire.model.User;
import com.questionnaire.service.IUserService;
import com.questionnaire.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author fruit123
 * @since 2018-02-22
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AnswerRepository answerRepository;

    @Override
    public List<User> findList() {
        return userRepository.findAll();
    }

    /**
     * 添加
     *
     * @param user
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public int save(User user) {
        //添加用户表
        user.setId(ToolUtil.getUuid());
        userRepository.save(user);
        //添加答案表
        if (ToolUtil.isNotEmpty(user.getAnsweList())) {
            for (int i = 0; i < user.getAnsweList().size(); i++) {
                Answer answer = user.getAnsweList().get(i);
                if (answer.getType() == 2) {
                    List<String> list = ToolUtil.getSplit(answer.getValue());
                    if (ToolUtil.isNotEmpty(list)) {
                        for (int j = 0; j < list.size(); j++) {
                            answer.setValue(list.get(j));
                            answer.setId(ToolUtil.getUuid());
                            answer.setUserid(user.getId());
                            answerRepository.save(answer);
                        }
                    }

                } else {
                    answer.setId(ToolUtil.getUuid());
                    answer.setUserid(user.getId());
                    answerRepository.save(answer);
                }

            }
        }
        return 1;
    }

    @Override
    public User checkByPhone(String phone) {
        User user = userRepository.findByPhone(phone);
        return user;
    }
}
